package com.bfs.service.hystrix.collaspers;/**
 * @Deacription TODO
 * @Author baohuajie
 * @Date 2020/12/13 23:15
 * @Version 1.0
 **/

import cfk.pojo.order.CustQueryReq;
import cfk.pojo.order.CustQueryResp;
import com.google.common.util.concurrent.SettableFuture;
import com.netflix.hystrix.*;
import com.netflix.hystrix.HystrixCommand.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.List;
import java.util.UUID;

/**
 *@Deacription TODO
 *@Author baohuajie
 *@Date 2020/12/13 23:15
 *@Version 1.0
 **/
public class HystrixCollapseCommand extends HystrixCollapser<List<CustQueryResp>, CustQueryResp, CustQueryReq> {

    private final Logger log = LoggerFactory.getLogger(HystrixCollapseCommand.class);

    private QueryService queryService;
    private CustQueryReq custQueryReq;

    public HystrixCollapseCommand(QueryService queryService, CustQueryReq custQueryReq) {
        super(setter());
        this.queryService = queryService;
        this.custQueryReq = custQueryReq;
    }


    @Override
    public CustQueryReq getRequestArgument() {
        CustQueryReq custQueryReq = new CustQueryReq();
        custQueryReq.setCustId(UUID.randomUUID().toString());
        return custQueryReq;
    }

    @Override
    protected HystrixCommand<List<CustQueryResp>> createCommand(Collection<CollapsedRequest<CustQueryResp, CustQueryReq>> collapsedRequests) {
        HystrixCommandBatch hystrixCommandBatch = new HystrixCommandBatch(queryService, "id");
        return hystrixCommandBatch;
    }

    @Override
    protected void mapResponseToRequests(List<CustQueryResp> batchResponse, Collection<CollapsedRequest<CustQueryResp, CustQueryReq>> collapsedRequests) {
        int count = 0;
        for (CollapsedRequest<CustQueryResp, CustQueryReq> request : collapsedRequests) {
            CustQueryResp resp = batchResponse.get(count++);
            request.setResponse(resp);
        }
    }

    private static Setter setter() {
        HystrixCollapserProperties.Setter setter = HystrixCollapserProperties.Setter();
        setter.withTimerDelayInMilliseconds(10);
        Setter hystrixCommandBatchKey = Setter.withCollapserKey(HystrixCollapserKey.Factory.asKey("hystrixCommandBatchKey")).andCollapserPropertiesDefaults(setter);

        return hystrixCommandBatchKey;
    }
}
